package services

import (
	"errors"
	"fmt"
	"longmen/server/pkg/common/helper/timehelper"
	utils2 "longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/db/mysql/db_sports"
	"longmen/server/pkg/db/redis/cache"

	"github.com/labstack/echo/v4"
	"longmen/server/pkg/common/api_models"
)

/*func (s *Service) GetCompetation4Crawler(req *api_models.GetCompetation4CrawlerReq) ([]*api_models.GetCompetation4CrawlerResp, error) {
	fName := "GetCompetation4CrawlerResp"
	o, err := repository.GetCompetation4Crawler(req.Date, req.Type)
	if err != nil {
		return nil, fmt.Errorf("%s%s", common.Convert(fName), err.Error())
	}
	return o, nil
}*/

/*func (s *Service) GetMatch4Crawler(req *api_models.GetMatch4CrawlerReq, uid uint) (*api_models.GetMatch4CrawlerResp, error) {
	fName := "GetMatch4Crawler"
	param := echo.Map{}
	var matchIds []int    //比赛ID
	var myMatchIds []uint //预约的比赛ID
	var flag bool
	anchorReservationList := make([]*api_models.GetAnchorReservation, 0)
	if req.Competation != "" {
		param["comp"] = req.Competation
	}
	if req.SportId != 0 {
		param["sport_id"] = req.SportId
	}
	if req.MatchStatus >= 1 && req.MatchStatus <= 3 {
		param["match_status"] = req.MatchStatus
	}
	if req.Date != "" {
		begin, end := util.INaDay2Unix(req.Date)
		param["match_time"] = map[string]interface{}{">=": begin, "<=": end}
	}
	if req.IsFlag == 2 {
		param["flag"] = 2
	}
	match4Crawler, count, soccerCount, basketballCount, err := repository.GetMatch4Crawler(param, req.Page, req.Size)
	if err != nil {
		return nil, fmt.Errorf("%s%s", common.Convert(fName), err.Error())
	}
	for _, matchTemp := range match4Crawler {
		matchIds = append(matchIds, matchTemp.MatchId)
	}
	if len(matchIds) > 0 {
		anchorReservationList, err = repository.GetAnchorReservation(matchIds)
		if err != nil {
			return nil, fmt.Errorf("%s%s", common.Convert(fName), err.Error())
		}
	}
	if uid > 0 {
		myMatchIds, err = repository.GetReservedMatchIds(uid)
		if err != nil {
			return nil, fmt.Errorf("%s%s", common.Convert(fName), err.Error())
		}
		flag = true
	}
	lives, err := repository.GetLivePbParam(map[string]interface{}{"status": 1, "matchid": map[string]interface{}{">": 1}}, "hot desc", 0, 0)
	matchList := make([]*api_models.Match4Crawler, 0)
	for _, matchTemp := range match4Crawler {
		reservation := make([]*api_models.Reservation, 0)
		var isReserved bool
		for _, anchor := range anchorReservationList {
			if anchor.MatchId == uint(matchTemp.MatchId) {
				reservation = append(reservation, &api_models.Reservation{
					ReceiveUid:     anchor.ReceiveUid,
					AnchorAvatar: anchor.AnchorAvatar,
				})
			}
		}
		for _, models_live := range lives {
			if int(models_live.Matchid) == matchTemp.MatchId {
				reservation = append(reservation, &api_models.Reservation{
					ReceiveUid:     uint(models_live.Anchorid),
					AnchorAvatar: models_live.AnchorAvatar,
				})
			}
		}
		if flag {
			for _, matchid := range myMatchIds {
				if int(matchid) == matchTemp.MatchId {
					isReserved = true
				}
			}
		}
		if matchTemp.HomeLogo == "" {
			matchTemp.HomeLogo = cache.GetConfigPub().DefaultMatchLogoUrl
		}
		if matchTemp.AwayLogo == "" {
			matchTemp.AwayLogo = cache.GetConfigPub().DefaultMatchLogoUrl
		}
		matchList = append(
			matchList,
			&api_models.Match4Crawler{
				MatchId:         matchTemp.MatchId,
				MatchEventTitle: matchTemp.Comp,
				MatchTime:       matchTemp.MatchTime,
				HomeTeamName:    matchTemp.Home,
				HomeTeamLogo:    matchTemp.HomeLogo,
				HomeScore:       int(matchTemp.HomeScore),
				AwayTeamName:    matchTemp.Away,
				AwayTeamLogo:    matchTemp.AwayLogo,
				AwayScore:       int(matchTemp.AwayScore),
				MatchStatus:     int(matchTemp.MatchStatus),
				IsReserved:      isReserved,
				Weights:         util.GetMatchWeights(matchTemp.Comp),
				SportId:         uint8(matchTemp.SportId),
				Reservation:     reservation,
			},
		)
	}
	return &api_models.GetMatch4CrawlerResp{
		Count:           count,
		SoccerCount:     soccerCount,
		BasketballCount: basketballCount,
		Match:           matchList,
	}, nil
}*/

func (s *Service) ReserveMatch4Crawler(matchId, uid, isAnchor, liveTime int) (*api_models.ReserveOrCancelReserveMatchResp, error) {
	match, err := db_sports.GetMatch4CrawlerByParam(echo.Map{"match_id": matchId, "match_status": 2}, "", "", 0, 0) // //比赛状态, 1-进行,2-未开赛,3-完场先查找是否有此场赛事
	if err != nil {
		return nil, err
	}
	if len(match) < 1 {
		return nil, errors.New("找不到此场赛事或赛事已经开始")
	}
	ok, err := db_sports.InsertUserMatchReservation(matchId, uid, isAnchor, liveTime)
	if err != nil {
		return nil, err
	}
	return &api_models.ReserveOrCancelReserveMatchResp{
		IsSuccess: ok,
	}, nil
}

func (s *Service) CancelReserveMatch4Crawler(matchId int, uId int) (*api_models.ReserveOrCancelReserveMatchResp, error) {
	ok := db_sports.DeleteUserMatchReservation(matchId, uId)
	return &api_models.ReserveOrCancelReserveMatchResp{
		IsSuccess: ok,
	}, nil
}

func (s *Service) GetReservedMatch4Crawler(uid int) ([]*api_models.GetReservedMatch4CrawlerResp, error) {
	fName := "GetReservedMatch4Crawler"
	var matchIds []int
	anchorReservationList := make([]*api_models.GetAnchorReservation, 0)
	matchList, err := db_sports.GetReservedMatch4Crawler(uid)
	if err != nil {
		return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
	}
	for _, match := range matchList {
		matchIds = append(matchIds, match.MatchId)
	}
	if len(matchList) > 0 {
		anchorReservationList, err = db_sports.GetAnchorReservation(matchIds)
		if err != nil {
			return nil, fmt.Errorf("%s%s", utils2.Convert(fName), err.Error())
		}
	}
	reservedMatch := make([]*api_models.ReservedMatch4Crawler, 0)
	for _, matchTemp := range matchList {
		reservation := make([]*api_models.Reservation, 0)
		for _, anchor := range anchorReservationList {
			if anchor.MatchId == uint(matchTemp.MatchId) {
				reservation = append(reservation, &api_models.Reservation{
					AnchorId:     anchor.AnchorId,
					AnchorAvatar: anchor.AnchorAvatar,
				})
			}
		}
		if matchTemp.HomeLogo == "" {
			matchTemp.HomeLogo = cache.GetConfigPub().DefaultMatchLogoUrl
		}
		if matchTemp.AwayLogo == "" {
			matchTemp.AwayLogo = cache.GetConfigPub().DefaultMatchLogoUrl
		}
		reservedMatch = append(reservedMatch, &api_models.ReservedMatch4Crawler{
			MatchId:         matchTemp.MatchId,
			MatchEventTitle: matchTemp.Comp,
			MatchTime:       matchTemp.MatchTime,
			HomeTeamName:    matchTemp.Home,
			HomeTeamLogo:    matchTemp.HomeLogo,
			HomeScore:       int(matchTemp.HomeScore),
			AwayTeamName:    matchTemp.Away,
			AwayTeamLogo:    matchTemp.AwayLogo,
			AwayScore:       int(matchTemp.AwayScore),
			MatchStatus:     int(matchTemp.MatchStatus),
			IsReserved:      true,
			Reservation:     reservation,
		})
	}
	resp := make([]*api_models.GetReservedMatch4CrawlerResp, 0)

	for _, match := range reservedMatch {
		var flag bool
		for _, warp := range resp {
			if timehelper.Stamp2Time(match.MatchTime).Format(timehelper.TIME_LAYOUT_FORMAT_4) == warp.Date {
				warp.Match = append(warp.Match, match)
				flag = true
			}
		}
		if flag {
			continue
		}
		matchResp := &api_models.GetReservedMatch4CrawlerResp{}
		matchResp.Date = timehelper.Stamp2Time(match.MatchTime).Format(timehelper.TIME_LAYOUT_FORMAT_4)
		matchResp.Match = append(matchResp.Match, match)
		resp = append(resp, matchResp)
	}
	return resp, nil
}
